/**
 * axios配置
 */
import axios from 'axios'
import pinia from '@/stores/index'
import setting from '@/config/setting'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'

let userStore = useUserStore(pinia)

// 设置统一的url
axios.defaults.baseURL = setting.api

/* 请求拦截器 */
axios.interceptors.request.use((config) => {
  // 添加token到header
  const token = userStore.token
  if (token) {
    config.headers[setting.tokenHeaderName] = token
  }
  config.headers['X-Requested-With'] = 'XMLHttpRequest'
  return config
}, (error) => {
  return Promise.reject(error)
})

/* 响应拦截器 */
axios.interceptors.response.use((res) => {
  let headerContent = res.headers['download-info'] ?? false
  if (headerContent) {
    return res
  }
  let code = res?.data?.code || null
  if (code !== 200) {
    message.error(res?.data?.msg || 'request code error')
  }

  return res.data
}, (error) => {
  console.log('接口请求失败')
  return Promise.reject(error)
})

export default axios
